package com.ja.openchat.ui;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

import com.google.gson.Gson;
import com.ja.openchat.R;
import com.ja.openchat.data.RegisterVue;
import com.ja.openchat.http.HttpVueClient;
import com.ja.openchat.ui.base.JaBaseFragment;
import com.just.agentweb.AgentWeb;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.zy.openchat.core.manager.AuthUserManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.model.config.TabExMenuInfo;
import com.zy.openchat.core.model.user.UserInfo;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import me.goldze.mvvmhabit.utils.KLog;

public class TabExWebFragment extends JaBaseFragment {
    @BindView(R.id.tv_bar_title)
    AppCompatTextView tvBarTitle;
    @BindView(R.id.iv_bar_right)
    AppCompatImageView ivBarRight;
    AgentWeb webView;
    @BindView(R.id.weblayout)
    FrameLayout weblayout;
    @BindView(R.id.iv_bar_back)
    View iv_bar_back;

    @Override
    protected int initLayout() {
        return R.layout.fragment_ex;
    }

    @Override
    protected void initDataAndEvent(Bundle savedInstanceState) {
        super.initDataAndEvent(savedInstanceState);
        ivBarRight.setVisibility(View.GONE);
        tvBarTitle.setText("");
        com.just.agentweb.WebViewClient webViewClient = new com.just.agentweb.WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url == null) return false;

                try {
                    if (!url.startsWith("http://") && !url.startsWith("https://")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) {//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }

                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                String webTitle = view.getTitle();
//                if (!TextUtils.isEmpty(webTitle)) {
//                    if (!TextUtils.equals(webTitle, "about:blank")) {
//                        tvBarTitle.setText(webTitle);
//                    }
//                }
            }

            @Override
            public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
                super.doUpdateVisitedHistory(view, url, isReload);
                iv_bar_back.setVisibility(webView.getWebCreator().getWebView().canGoBack() ? View.VISIBLE : View.GONE);
            }
        };
        webView = AgentWeb.with(this)
                .setAgentWebParent(weblayout, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator(getResources().getColor(R.color.CG1))
                .setWebViewClient(webViewClient)
                .createAgentWeb()
                .ready()
                .get();

        webView.getWebCreator().getWebView().addJavascriptInterface(this, "android");

        TabExMenuInfo curTabExMenuInfo = TabExMenuInfo.getTabExMenuInfo();
        if (curTabExMenuInfo != null && curTabExMenuInfo.isValid()) {
            tvBarTitle.setText(curTabExMenuInfo.title);
            webView.getUrlLoader().loadUrl(curTabExMenuInfo.url);
        }
        iv_bar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webView.back();
            }
        });
        tvBarTitle.postDelayed(new Runnable() {
            @Override
            public void run() {
                tvBarTitle.setSelected(true);
            }
        }, 200);
        WebSettings settings = webView.getAgentWebSettings().getWebSettings();
        settings.setJavaScriptEnabled(true);


    }

    @JavascriptInterface
    public String getAppToken() {
        String jsonStr = requireActivity().getSharedPreferences("config", Context.MODE_PRIVATE).getString("Access_token", null);
        return jsonStr;
    }

    @JavascriptInterface
    public String getUser() {
        String jsonStr = requireActivity().getSharedPreferences("config", Context.MODE_PRIVATE).getString("userInfo", null);
        return jsonStr;
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Tab_Ex_Menu_Changed: {
                TabExMenuInfo curTabExMenuInfo = TabExMenuInfo.getTabExMenuInfo();
                if (curTabExMenuInfo != null && curTabExMenuInfo.isValid()) {
                    KLog.d("EUser_Tab_Ex_Menu_Changed curTabExMenuInfo.url==" + curTabExMenuInfo.url);
                    tvBarTitle.setText(curTabExMenuInfo.title);
                    webView.getUrlLoader().loadUrl(curTabExMenuInfo.url);
                }
            }
            break;
        }
    }
}